from log import err, out
from net import push_log, center_post
from common import parse_param
from json import loads


class Task:

    def __init__(self, center, key, data, **kwargs):
        self.task_params = parse_param(data)
        if isinstance(self.task_params, dict):
            self.__dict__.update(self.task_params)

        self.center_uuid = center
        self.center_key = key
        options = loads(kwargs.get('options', '{}'))
        self.center_options = {}
        for k, v in options.items():
            self.center_options[k] = loads(v) if v else v

    def push(self, client, title, op, **data):
        if data is None:
            data = {}
        israise = data.pop('israise', True)
        data['center'] = self.center_uuid
        data['wid'] = client
        data['type'] = title
        data['op'] = op
        #  out('Push: ', data)
        r = center_post(action='/push', **data)
        if israise and r['code']:
            raise Exception('推送%s: %s' % (title, r))
        #  out('Push Status: ', r)
        return r

    def __call__(self, *args, **kwargs):
        """
        任务执行入口
        """
        out('Task Start(%s): %s' % (self, self.task_params))
        try:
            return self.run()
        except Exception as e:
            if hasattr(self, 'quit'):
                self.quit('exception', israise=False)
            content = err('%s 任务执行出错: %s' % (self, e), stack=True)
            content = '%s\n%s' % (self.task_params, content)
            return push_log('任务执行出错: %s' % e, content)

